package designPatterns.behaviorMode.iterator;

/**
 * Created by thinkpad on 2015/8/13.
 * Iterator pattern is used to iterate through a collection of objects. It is a commonly used pattern, you probably have used it before. Whenever you sees something like hasNext() and next(), it is probably a iterator pattern.
 * For example, you may iterate through a list of database query record.
 */
interface IIterator{
    public boolean hasNext();
    public Object next();
}

interface IContainer{
    public IIterator createIterator();
}

class RecordCollection implements IContainer{
    private String recordArray[] = {"first","second","third","fourth","fifth"};

    public IIterator createIterator(){
        RecordIterator iterator = new RecordIterator();
        return iterator;
    }

    private class RecordIterator implements IIterator{
        private int index;

        public boolean hasNext(){
            if (index < recordArray.length)
                return true;
            else
                return false;
        }

        public Object next(){
            if (this.hasNext())
                return recordArray[index++];
            else
                return null;
        }
    }
}

public class TestIterator {
    public static void main(String[] args) {
        RecordCollection recordCollection = new RecordCollection();
        IIterator iter = recordCollection.createIterator();

        while(iter.hasNext()){
            System.out.println(iter.next());
        }
    }
}

